package com.xavier.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xavier.dao.UserRoleMapper;
import com.xavier.model.UserRole;
import com.xavier.service.IUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 业务逻辑层-用户角色实现类
 *
 * @author Xavier
 * @version 1.0
 */
@Slf4j
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements IUserRoleService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createUserRole(Long userId, List<Long> roleIds) {
        if (ObjectUtil.isEmpty(roleIds)) {
            return;
        }
        List<UserRole> beanList = new ArrayList<>();
        for (Long roleId : roleIds) {
            UserRole bean = new UserRole();
            bean.setUserId(userId);
            bean.setRoleId(roleId);
            beanList.add(bean);
        }
        super.saveBatch(beanList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserRole(Long userId, List<Long> roleIds) {
        remove(UserRole.gw().eq(UserRole::getUserId, userId));
        createUserRole(userId, roleIds);
    }

    @Override
    public List<Long> getUserRole(Long userId) {
        List<UserRole> list = list(UserRole.gw().eq(UserRole::getUserId, userId));
        return ObjectUtil.isEmpty(list) ? null : list.stream().map(UserRole::getRoleId).collect(Collectors.toList());
    }

}
